package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Version5     登录与退出   功能：可以加在V3
 *
 */

public class Server {
    private ServerSocket serverSocket;
    private static final Integer PORT = 191;
    private List<PrintWriter> allOut = new ArrayList<>();
    //1.私有化一个属性：存账号和密码
    private static final CopyOnWriteArrayList<String>onlineUsers=new CopyOnWriteArrayList<>();
    private Map<String, String> userDatabase;

    public Server() {
        try {
            serverSocket = new ServerSocket(PORT);
            //创建Map对象
            userDatabase = new HashMap<>();
            userDatabase.put("耶耶", "9966");
            userDatabase.put("土豆土豆", "0101");
            userDatabase.put("地瓜地瓜", "0707");
        } catch (BindException e) {
            System.out.println("请检查端口号，被占用~~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("客户端连接断开连接~~~");
        } finally {
            if (serverSocket != null && serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败~~~~");
                }
                System.out.println("服务器关闭成功~~Over~~~");
            }
        }
    }

    public static void main(String[] args) {
        new Server().start();
    }


    private synchronized void broadcastMessage(String message) {

        for (PrintWriter pw : allOut) {
            pw.println("消息广播：" + message);
            pw.println("请输入消息(输入exit退出):" );
        }
        for (String user:onlineUsers){
            System.out.println(message);
        }
    }
  private synchronized void updateOnlineUsers(){
      String userList="在线用户："+String.join("、",onlineUsers);
      for (PrintWriter pw : allOut) {
          pw.println(userList);
      }
  }


    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;
        //4.线程中：确定那个客户端---赋予功能
        private String username;
        private String password;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

                synchronized (allOut) {//监视器集合，只允许一个客户端过来
                    //来客户端.添加可以写出的方法
                    allOut.add(pw);//目的：客户端，写出消息---分发消息
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接了~~~~");
            }
        }

        //5.5因为用户账号可能很多，封装Login,传入参数判断
        private boolean Login(String user, String pass) {
            return userDatabase.containsKey(user) && userDatabase.get(user).equals(pass);
        }

        //6.handleChat 封装：关闭   ---放入线程中
        private void handleChat() {
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {//读入客户端
                        System.out.println(ip + "客户端说：" + message);
                        System.out.print("服务器请输入：");
                        //理解：客户端写出----服务器读入
                        //  转发内容：客户端写出服务器端读入的内容
                        broadcastMessage(message);
                        pw.println("请输入聊天内容（输入exit退出）：");
                        if("exit".equalsIgnoreCase(message)){
                            synchronized (onlineUsers){
                                onlineUsers.remove(username);
                            }
                            updateOnlineUsers();
                            System.exit(0);
                        }else{
                            System.out.println(username+":"+message);
                        }
                    }
                } catch (IOException e) {
                    System.out.println(username+"退出~~~");
                }
            }).start();

            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("服务器输入：");
                String sme = input.nextLine();
                pw.println("服务器说：" + sme);

                System.out.println("写出完毕");
                String say=new String();
                if (say.equalsIgnoreCase("exit")) {
                    System.out.println(username + "客户端断开链接啦~IP是：" + ip);
                    break;
                }
            }
        }
            public void run () {
                try {
                    //5.当客户端进行读写功能前，加入登录功能
                    //交互问题：服务器---客户端发送：文本
                    //         客户端---服务器接收：文本
                    //5.1向客户端发送一个消息提醒：请输入用户名：
                    pw.println("请输入用户名");
                    //5.2客户端输入账号【服务器端读取】
                    username = br.readLine();
                    pw.println("请输入密码");
                    password = br.readLine();
                    //5.3服务器端：判断账号与密码
                    //5.4用户可能很多个，封装方法Login:判断账号密码
                    if (Login(username, password)) {
                        pw.println("登陆成功，欢迎进入耶耶牌聊天室");
                        //聊天功能  封装方法：读写功能  handleChat
                        String username= br.readLine();
                        synchronized (onlineUsers){
                            onlineUsers.add(username);
                        }
                        updateOnlineUsers();
                        handleChat();
                    } else {
                        pw.println("登录失败，用户名或者密码错误！！！");
                        socket.close();//关闭
                    }

                } catch (IOException e) {
                    System.out.println("服务器端读写出问题");

                } finally {
                    //一个客户端已经转发完毕了，移除当前客户端写出功能
                    synchronized (allOut) {//目的：移除，刚刚链接客户端
                        allOut.remove(pw);
                    }
                    updateOnlineUsers(); // 更新在线用户列表
                    synchronized (allOut) {
                        allOut.remove(pw); // 从输出流列表中移除当前客户端的输出流
                    }
                    if (pw != null)
                        pw.close();
                    if (br != null)
                        try {
                            br.close();
                        } catch (IOException e) {
                            System.out.println("读入流断开连接~~");
                        }

                    if (socket != null && !socket.isClosed()) {
                        System.out.println(ip + "客户端退出服务链接~~~");
                        try {
                            socket.close();
                        } catch (IOException e) {
                            System.out.println(ip+"客户端退出服务器链接~~");
                        }
                    }
                }

            }
        }

    }

